import Taro from "@tarojs/taro";
import { isEmpty } from "./kit";
const TOKEN_KEY = "auth_token";
const USER_INFO = "user_info";
export const setToken = (token: string) => {
  try {
    Taro.setStorageSync(TOKEN_KEY, token);
    return true;
  } catch (error) {
    console.error("存储Token失败:", error);
    return false;
  }
};

export const getToken = () => {
  try {
    return Taro.getStorageSync(TOKEN_KEY) || null;
  } catch (error) {
    console.error("获取Token失败:", error);
    return null;
  }
};

export const removeToken = () => {
  try {
    Taro.removeStorageSync(TOKEN_KEY);
    return true;
  } catch (error) {
    console.error("清除Token失败:", error);
    return false;
  }
};

export const isAuthenticated = () => {
    return !!getToken()
}

export const setInfo = (info:any) => {
  try {
    Taro.setStorageSync(USER_INFO, info);
    return true;
  } catch (error) {
    return false;
  }
}
export const getInfo = () => {
  try {
    let userInfo =  Taro.getStorageSync(USER_INFO) || null;
    if(isEmpty(userInfo)){
      removeUserInfo();
      Taro.reLaunch({
        url:"/pages/login/index"
      })
      return null;
    }
    return userInfo;
  } catch (error) {
    return null;
  }
}
export const removeUserInfo = () => {
  try {
    Taro.removeStorageSync(USER_INFO);
    return true;
  } catch (error) {
    return false;
  }
};

